//
//  AFNworkTools.swift
//  ShangHaiWeiBo
//
//  Created by 蔡杰 on 16/2/26.
//  Copyright © 2016年 蔡杰. All rights reserved.
//
import Foundation
import UIKit
import AFNetworking
/**
 网络请求的格式的枚举
 
 - GET:  GET请求
 - POST: POST请求
 */
enum CZRequestMethod:String{
    
    case GET = "GET"
    case POST = "POST"
}

class AFNworkTools: AFHTTPSessionManager {
    //MARK: - 应用程序信息
    let AppKey:String = "350128097"
    let AppSecret:String = "909cfa4ae5fc4cdf9a5e4ac0274de01d"
    let redirectUri:String = "https://www.baidu.com/"
    /**
     *  单列
     */
    static var sharedTools:AFNworkTools = {
        
        let lools = AFNworkTools(baseURL: nil)
        lools.responseSerializer.acceptableContentTypes?.insert("text/plain")
         (lools.responseSerializer as! AFJSONResponseSerializer).removesKeysWithNullValues = true
        lools.reachabilityManager.startMonitoring()
        return lools
    }()
    
    deinit {
    
        reachabilityManager.stopMonitoring()
    }
    
    var reachable: Bool {
        return reachabilityManager.reachable
    }
    
    func request(method: CZRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: (result: [String: AnyObject]?)->()){
        
        //成功回调
        let success = {(task: NSURLSessionDataTask,responseObject:AnyObject?) -> Void in
            
            if let response = responseObject as? [String:AnyObject] {
                
                finished(result: response)
            } else {
                
                print("格式错误")
                finished(result: nil)
            }
        }
        //失败回调
        let failure  = {(task: NSURLSessionDataTask?, error:NSError) -> Void in
            
            finished(result: nil)
            
        }
        if method == .GET {
            // GET 请求
            GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            // POST 请求
            POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }

    }
}
